var amqp = require('amqp');
var ui_pub_sub = require('../db/Ui_pub_sub_collection_If');
var path = require('path');
var log4js = require('../httpServer/utils/logger');
var config = require('../config');

var Logger = log4js.getLogger(path.basename(__filename));
Logger.setLevel(config.LogLevel);

var connection = amqp.createConnection();
var EXCHANGE = 'makeblock-iot-topics';

function runServer() {
	
	connection.on('ready', function() {
		Logger.info('[line:' + __line + ']' + ' ready');
		connection.queue('shansjlin', {durable: true, autoDelete: false}, function(queue) {
			Logger.info('[line:' + __line + ']' + ' Queue:' + queue.name + ' created');
			queue.bind(EXCHANGE, '#', function() {
                Logger.info('bind exchange:' + EXCHANGE + ' ok');
                queue.subscribe(function(message, header, deliveryInfo, messageObject) {
                	var routingKey = deliveryInfo.routingKey;
                	var data = message.data.toString();
                	if(routingKey.indexOf('$SYS.') == -1) {
                		Logger.debug('recv routingKey:' + routingKey + ', data:' + data);
                		ui_pub_sub.Insert(routingKey, data).then(function(msg) {
                			Logger.debug(msg);
                		}).catch(function(err, msg) {
                			Logger.error('[line:' + __line + ']' + ' err:' + err + ', msg:' + msg);
                		});
                	} else {
                		Logger.info('[line:' + __line + ']' + ' new clientId:' + data + ', new subscribed topic:' + routingKey);
                	}
                	// messageObject.acknowledge(false);
				});
            });
		});
	});

	connection.on('error', function(e) {
		Logger.error("Error from amqp: " + e);
	});
}

exports.runServer = runServer;